/***************************************************************************
 *   Copyright (C) 2007 by Leonid Krashenko   *
 *   krashenko@mail.ru   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
	
#include "CommonFunctions.h"

#include <string>
#include <cstdlib>
			
namespace neiderra
{ 
	namespace utils 
	{
		void strreverse(char* begin, char* end) {
			char aux;
			while(end>begin)
			aux=*end, *end--=*begin, *begin++=aux;
		}
	}
}

using neiderra::utils::strreverse;

void neiderra::utils::itoa(int value, char* str, int base) {
	using namespace std;
			
	char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";
	char* wstr=str;
	int sign;
	div_t res;
			
			// Validate base
	if (base<2 || base>35){ *wstr='\0'; return; }
			
			// Take care of sign
	if ((sign=value) < 0) value = -value;
			
	// Conversion. Number is reversed.
	do {
		res = div(value,base);
		*wstr++ = num[res.rem];
	}while(value=res.quot);
			
	if(sign<0) *wstr++='-';
	*wstr='\0';
			
	// Reverse string
	strreverse(str,wstr-1);
}

std::string neiderra::utils::intToStr(int value)
{
	char buf[20];
	utils::memset(buf, 0, 20);
	itoa(value, buf, 10);
	std::string sval(buf);
	return sval;
}
